//
//  XXButton.swift
//  aquariumstudio
//
//  Created by zj on 2022/10/19.
//  Copyright © 2022 LXF. All rights reserved.
//

import UIKit

public extension UIButton {

    enum Layout{
        case imgLeft
        case imgRight
        case imgTop
        case imgBottom
    }
    
    func resetLayout() {
        self.titleEdgeInsets = .zero;
        self.imageEdgeInsets = .zero;
    }
    func setLayout(layout:Layout,space:CGFloat,offset:UIEdgeInsets = .zero) {
        /**
         
         *  知识点：titleEdgeInsets是title相对于其上下左右的inset，跟tableView的contentInset是类似的，
         
         *  如果只有title，那它上下左右都是相对于button的，image也是一样；
         
         *  如果同时有image和label，那这时候image的上左下是相对于button，右边是相对于label的；title的上右下是相对于button，左边是相对于image的。
         
         */
        
        // 1. 得到imageView和titleLabel的宽、高
        
        let imageWith = self.imageView?.image?.size.width ?? 0;

        let imageHeight = self.imageView?.image?.size.height ?? 0;

        var labelWidth:CGFloat = 0.0;

        var labelHeight:CGFloat = 0.0;
 
        labelWidth = self.titleLabel?.intrinsicContentSize.width ?? 0;

        labelHeight = self.titleLabel?.intrinsicContentSize.height  ?? 0;

//        // 2. 声明全局的imageEdgeInsets和labelEdgeInsets
//
        var imageEdgeInsets = UIEdgeInsets.zero;
        var labelEdgeInsets = UIEdgeInsets.zero;

//        // 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
//
        switch (layout) {
        case .imgTop:

            imageEdgeInsets = UIEdgeInsets.init(top: -labelHeight-space/2.0, left: 0, bottom: 0, right: -labelWidth)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith, bottom: -imageHeight-space/2.0, right: 0);

        case .imgLeft:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -space/2.0, bottom: 0, right: space/2.0);
            labelEdgeInsets = UIEdgeInsets(top: 0, left: space/2.0, bottom: 0, right: -space/2.0);
            
        case .imgBottom:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight-space/2.0, right: -labelWidth);
            labelEdgeInsets = UIEdgeInsets(top: -imageHeight-space/2.0, left: -imageWith, bottom: 0, right: 0);

        case .imgRight:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth+space/2.0, bottom: 0, right: -labelWidth-space/2.0);
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith-space/2.0, bottom: 0, right: imageWith+space/2.0);
      
        }

       // 4. 赋值
        self.titleEdgeInsets = labelEdgeInsets.add(other: offset);
        self.imageEdgeInsets = imageEdgeInsets.add(other: offset);
    }

}
